# 合并图片
import os
from PIL import Image
import re

def get_image_number(filename):
  """
  从文件名中提取数字
  :param filename: 文件名
  :return: 提取到的数字，如果没有则返回 -1
  """
  match = re.search(r'_(\d+)\.\w+', filename)
  if match:
    return int(match.group(1))
  return -1

def combine_images(directory):
  """
  读取指定目录下的图片，按名称中的数字升序排列后拼接成一张长图
  :param directory: 图片所在目录
  """
  # 获取目录下所有图片文件
  image_files = [f for f in os.listdir(directory) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
  # 按文件名中的数字升序排序
  image_files.sort(key = get_image_number)

  images = []
  max_width = 0
  total_height = 0

  # 打开所有图片，计算最大宽度和总高度
  for image_file in image_files:
    image_path = os.path.join(directory, image_file)
    image = Image.open(image_path)
    images.append(image)
    max_width = max(max_width, image.width)
    total_height += image.height

  # 创建一个空白的长图
  combined_image = Image.new('RGB', (max_width, total_height))
  current_height = 0

  # 将每张图片粘贴到长图上
  for image in images:
    combined_image.paste(image, (0, current_height))
    current_height += image.height

  # 获取目录名称
  dir_name = os.path.basename(os.path.normpath(directory))
  # 以目录名称作为文件名保存合并后的长图
  output_filename = f"{dir_name}.jpg"
  output_path = os.path.join(directory, output_filename)
  combined_image.save(output_path)
  print(f"图片合并完成，合并后的图片已保存为 {output_filename}")

if __name__ == "__main__":
  directory = r'C:\Users\Administrator\Desktop\临时'  # 请替换为实际的图片目录
  combine_images(directory)
